import axios from 'axios'
import { ElNotification } from 'element-plus'
import { jwt } from '../utils/jwt.js'

// 携带cookie
// axios.defaults.withCredentials = import.meta.env.VITE_APP_SECURITY_TYPE === 'session';


// create an axios instance
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API, // url = base url + request url
    withCredentials: import.meta.env.VITE_APP_SECURITY_TYPE === 'session', // true send cookies when cross-domain requests
    timeout: 50000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // console.log("VITE_APP_SECURITY_TYPE = [" + import.meta.env.VITE_APP_SECURITY_TYPE + ']')
        // console.log(typeof import.meta.env.VITE_APP_SECURITY_TYPE)
        // console.log("is jwt = " + (import.meta.env.VITE_APP_SECURITY_TYPE === 'jwt'))
        // console.log('token = ' + jwt.token)
        // do something before request is sent
        if (import.meta.env.VITE_APP_SECURITY_TYPE === 'jwt' && jwt.token) {
            config.headers['Authorization'] = 'Bearer ' + jwt.token
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data

        // if the custom code is not 20000, it is judged as an error.
        if (res.code !== 200) {
            return Promise.reject(res)
        } else {
            return res
        }
    },
    error => {
        console.debug('have aa error ' + error.message)// for debug
        console.debug('err ' + error.response.status) // for debug
        console.debug(error.response)
        if (error.response.status === 401) {
            ElNotification({
                title: '缺少权限',
                message: '请先登录，或者使用有操作权限的用户登录。',
                type: 'error'
            })
            jwt.logout()
        } else {
            ElNotification({
                title: '失败',
                message: error.response.data?.message || error.message,
                type: 'error'
            })
        }
        return Promise.reject(error.response.data)
    }
)

export default service
